package com.irs.irsforum.service.impl;

import com.irs.irsforum.entity.Behavior;
import com.irs.irsforum.entity.Post;
import com.irs.irsforum.mapper.BehaviorMapper;
import com.irs.irsforum.mapper.PostMapper;
import com.irs.irsforum.service.IBehaviorService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.irs.irsforum.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yihuili
 * @since 2020-01-18
 */
@Service
public class BehaviorServiceImpl extends ServiceImpl<BehaviorMapper, Behavior> implements IBehaviorService {

    @Autowired
    BehaviorMapper behaviorMapper;
    @Autowired
    PostMapper postMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setBehaviorType(Long postId, Long userId, Integer behaviorType) {
        Post post  = postMapper.getProSubById(postId);
        Behavior newBehavior;
        if(post == null ){
            newBehavior = new Behavior(userId, postId, TimeUtil.getSqlTime(), behaviorType, null, null);
        }else{
            newBehavior = new Behavior(userId, postId, TimeUtil.getSqlTime(), behaviorType, post.getProblemId(), post.getSubjectId());
        }
        Behavior behavior = behaviorMapper.getBehavior(postId, userId);
        if(behavior != null){
            Integer type = behavior.getBehaviorType();
            if(type == 0 || type.equals(behaviorType)){}
            else{
                behaviorMapper.updateBehavior(newBehavior);
            }
        }else{
            behaviorMapper.setBehavior(newBehavior);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBehavior(Long postId, Long userId, Integer behaviorType) {
        behaviorMapper.updateBehavior(new Behavior(userId, postId, behaviorType, TimeUtil.getSqlTime()));
    }
}
